import { useState, useCallback, useEffect, useRef } from 'react';
import { useDrag } from 'react-dnd';
import { COMMANDS } from '@repo/executor/src/playback_tree/constants';
import './index.css';

type NodeData = {
  cmd: string,
  name?: string,
  type: 'folder' | 'file',
  expanded?: boolean,
  children?: NodeData[]
}

// 系统预置数据
const presetData: NodeData[] = [
  {
    cmd: 'flowControl',
    name: '流程控制',
    type: 'folder',
    expanded: false,
    children: [
      {
        cmd: 'if',
        type: 'file',
      },
      {
        cmd: 'elseIf',
        type: 'file',
      },
      {
        cmd: 'else',
        type: 'file',
      },
      {
        cmd: 'while',
        type: 'file',
      },
      {
        cmd: 'times',
        type: 'file',
      },
      {
        cmd: 'do',
        type: 'file',
      },
      {
        cmd: 'repeatIf',
        type: 'file',
      },
      {
        cmd: 'break',
        type: 'file',
      },
      {
        cmd: 'continue',
        type: 'file',
      },
      {
        cmd: 'pause',
        type: 'file',
      },
      {
        cmd: 'gotoLabel',
        type: 'file',

      },
      {
        cmd: 'label',
        type: 'file',

      },
      {
        cmd: 'end',
        type: 'file',

      },
    ]
  },
  {
    cmd: 'broswer',
    name: '浏览器',
    type: 'folder',
    expanded: false,
    children: [
      {
        cmd: 'createBrowser',
        type: 'file',

      },
      {
        cmd: 'open',
        type: 'file',

      },
      {
        cmd: 'click',
        type: 'file',

      },
      {
        cmd: 'doubleClick',
        type: 'file',

      },
      {
        cmd: 'close',
        type: 'file',
      },
      {
        cmd: 'closeBrowser',
        type: 'file',
      },
    ]
  }
]

// 上下文菜单组件
const ContextMenu = ({ position, items, onClose }) => {
  if (!position) return null;

  return (
    <div
      className="context-menu"
      style={{
        position: 'absolute',
        left: position.x,
        top: position.y,
        zIndex: 1000
      }}
      onClick={(e) => e.stopPropagation()}
    >
      <ul>
        {items.map((item, index) => (
          <li
            key={index}
            onClick={() => {
              item.action();
              onClose();
            }}
            className="context-menu-item"
          >
            {item.label}
          </li>
        ))}
      </ul>
    </div>
  );
};

// 文件树节点组件
const TreeNode = ({
  node,
  depth,
  onToggle,
  onSelect,
  onContextMenu,
}) => {
  const [{ isDragging }, drag] = useDrag(() => ({
    type: 'CMD',
    item: { ...node, type: 'CMD', cmd: node.cmd, index: -1, dragIndex: -1 },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  }), [node]);

  const isFolder = node.type === 'folder';
  const isSelected = onSelect?.id === node.id;

  return (
    <div
      ref={(node) => {
        if (!isFolder) {
          drag(node)
        }
      }}
      style={{ opacity: isDragging ? 0.5 : 1 }}
      className="tree-node"
      onContextMenu={(e) => {
        e.preventDefault();
        e.stopPropagation();
        onContextMenu(e, node);
      }}
    >
      <div
        className={` ${isFolder ? 'folder' : 'file'}   ${isSelected ? 'selected' : ''} `}
        onClick={() => {
          if (isFolder) {
            onToggle(node.id);
          } else {
            onSelect(node);
          }
        }}
      >
        <span className="icon">
          {isFolder ? (node.expanded ? '📂' : '📁') : '📄'}
        </span>
        <span className="name" title={COMMANDS.get(node.cmd)?.name}>{isFolder ? node.name : COMMANDS.get(node.cmd)?.name || node.cmd}</span>
      </div>
      {isFolder && node.expanded && node.children && (
        <div className="children" style={{ paddingLeft: `${depth * 16}px` }}>
          {node.children.map((child: any) => (
            <TreeNode
              key={child.id}
              node={child}
              depth={depth + 1}
              onToggle={onToggle}
              onSelect={onSelect}
              onContextMenu={onContextMenu}
            />
          ))}
        </div>
      )}
    </div>
  );
};

// 文件资源管理器组件
const FileExplorer = () => {

  const [fileTree, setFileTree] = useState([]);
  const [selectedFile, setSelectedFile] = useState(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [filteredTree, setFilteredTree] = useState<any[]>([]);

  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const [contextMenu, setContextMenu] = useState(null);

  const rootDropRef = useRef(null);

  // 关闭上下文菜单
  const closeContextMenu = useCallback(() => {
    setContextMenu(null);
  }, []);

  // 处理上下文菜单
  const handleContextMenu = useCallback((e, node: NodeData) => {
    setContextMenu({
      position: { x: e.clientX, y: e.clientY },
      node
    });
  }, []);

  // 渲染上下文菜单项
  const getContextMenuItems = useCallback(() => {
    const items = [
      {
        label: '收藏',
        action: () => { }
      },
      {
        label: '查找引用',
        action: () => { }
      }
    ];
    return items;
  }, []);

  // 读取目录内容并构建文件树
  const fetchCmdList = useCallback(async () => {
    try {
      setIsLoading(true);
      setError('');

      // 通过IPC调用主进程读取目录
      const items = presetData;

      const buildTree: any = (items: NodeData[]) => {
        return items.map((item: NodeData) => {
          if (item.type === 'folder') {
            return {
              id: item.cmd,
              name: item.name,
              cmd: item.cmd,
              type: 'folder',
              expanded: false,
              children: buildTree(item.children || [])
            };
          } else {
            return {
              id: item.cmd,
              name: item.name,
              cmd: item.cmd,
              type: 'file'
            };
          }
        });
      };

      const tree = buildTree(items);
      return tree;
    } catch (err: any) {
      setError(err.message);
      return [];
    } finally {
      setIsLoading(false);
    }
  }, []);

  // 加载文件夹内容
  const loadFolder = useCallback(async () => {
    const tree = await fetchCmdList();
    setFileTree(tree);
    setFilteredTree(tree);
  }, [fetchCmdList]);

  // 切换文件夹展开状态
  const toggleFolder = useCallback(async (id) => {
    setFileTree(prevTree => {
      const updateTree = (nodes) => {
        return nodes.map(node => {
          if (node.id === id && node.type === 'folder') {
            return { ...node, expanded: !node.expanded };
          }
          if (node.children) {
            return { ...node, children: updateTree(node.children) };
          }
          return node;
        });
      };
      return updateTree(prevTree);
    });
  }, [fetchCmdList]);

  // 过滤文件树
  const filterTree = useCallback((nodes, term) => {
    if (!term) return nodes;

    return nodes.filter(node => {
      if (node.children) {
        const filteredChildren = filterTree(node.children, term);
        if (filteredChildren.length > 0) {
          return { ...node, children: filteredChildren };
        }
      }
      return node.name.toLowerCase().includes(term.toLowerCase());
    });
  }, []);

  // 当搜索词变化时更新过滤后的树
  useEffect(() => {
    if (searchTerm) {
      setFilteredTree(filterTree(fileTree, searchTerm));
    } else {
      setFilteredTree(fileTree);
    }
  }, [searchTerm, fileTree, filterTree]);

  // 初始化：加载用户主目录
  useEffect(() => {
    loadFolder();
  }, []);

  return (
    <div className="cmd-explorer-container overflow-auto h-full" onClick={closeContextMenu}>
      {/* 上下文菜单 */}
      {contextMenu && (
        <ContextMenu
          position={contextMenu.position}
          items={getContextMenuItems(contextMenu.node)}
          onClose={closeContextMenu}
        />
      )}

      {/* 命令管理器内容 */}
      <div className="explorer-header">
        <div className="header-title">
          <span className="icon">📁</span>
          <h3>标准指令</h3>
        </div>
        <div className="search-box">
          <input
            type="text"
            placeholder="搜索命令..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
          <span className="search-icon">🔍</span>
        </div>
      </div>
      <div
        ref={rootDropRef}
        className={`file-tree`}
        onClick={closeContextMenu}
      >
        {isLoading ? (
          <div className="loading-indicator">
            <div className="spinner"></div>
            <p>加载中...</p>
          </div>
        ) : error ? (
          <div className="error-message">
            <span className="error-icon">⚠️</span>
            <p>{error}</p>
          </div>
        ) : filteredTree.length > 0 ? (
          filteredTree.map(node => (
            <TreeNode
              key={node.id}
              node={node}
              depth={0}
              onToggle={toggleFolder}
              onSelect={setSelectedFile}
              onContextMenu={handleContextMenu}
            />
          ))
        ) : (
          <div className="no-results">
            <p>数据为空</p>
          </div>
        )}
      </div>
    </div>
  );
};

export default FileExplorer;
